#ifndef MODULES_EVENT_EVENTSERVICE_H_
#define MODULES_EVENT_EVENTSERVICE_H_
#include "../common.h"

#ifdef  CONFIG_EVENT_CLOSE_THREAD__
const bool _openThread = false;
#else
const bool _openThread = true;
#endif

namespace _EventService {
template<typename T>
//https://blog.csdn.net/wisdom605768292/article/details/9881419
//声明类型不加 typename 调用count永远找不到。。。。
typename std::map<EVENT_KEY, std::vector<TaskFunction<T>> > _eventHandle;
}

class EventService {
public:
	template<typename T>
	static void registerHandle(EVENT_KEY key, TaskFunction<T> fun) {
		if (_EventService::_eventHandle<T>.count(key) == 0) {
			_EventService::_eventHandle<T>[key] = std::vector<TaskFunction<T>>();
		}
		std::vector<TaskFunction<T>> *ve = &_EventService::_eventHandle<T>[key];
		ve->push_back(fun);
	}

	template<typename T>
	static void trigger(EVENT_KEY key, TaskCtx<T> *ctx) {
		if (_EventService::_eventHandle<T>.count(key) == 0) {
			return;
		}
		std::vector<TaskFunction<T>> *listeners = &_EventService::_eventHandle<T>[key];

		if (ctx != nullptr) {
			size_t taskSize = listeners->size();
			ctx->initTaskSize(taskSize);
		}

		for (auto &listener : *listeners) {
			if (_openThread) {
				Task::run(listener, ctx);
			} else {
				listener(ctx);
			}
		}
		if (ctx != nullptr&& !_openThread) {
			ctx->gc();
		}
	}

	static void trigger(EVENT_KEY key) {
		TaskCtx<void*> *ctx = nullptr;
		trigger(key, ctx);
	}
};

#endif /* MODULES_EVENT_EVENTSERVICE_H_ */
